package work.soho.proxy.aliyun.parts;

import com.aliyuncs.ecs.model.v20140526.CreateVSwitchRequest;
import com.aliyuncs.ecs.model.v20140526.CreateVSwitchResponse;
import com.aliyuncs.ecs.model.v20140526.DescribeVSwitchesRequest;
import com.aliyuncs.ecs.model.v20140526.DescribeVSwitchesResponse;

public class SwitchPart extends BasePart implements IPart{
    /**
     * 默认交换机
     */
    private String vSwitchName = "proxySocket5switch";

    /**
     * switch id
     */
    private String vSwitchId = "";

    @Override
    public boolean isExist() {
        try {
            return getId() != null;
        } catch (Exception e) {
            //ignore
        }
        return false;
    }

    /**
     * 获取对应的switch ID
     *
     * @return
     */
    public String getId() {
        DescribeVSwitchesRequest describeVSwitchesRequest = new DescribeVSwitchesRequest();
        DescribeVSwitchesResponse describeVSwitchesResponse = callOpenApi(describeVSwitchesRequest);
        for (DescribeVSwitchesResponse.VSwitch vSwitch:describeVSwitchesResponse.getVSwitches()) {
            if(vSwitch.getVSwitchName().equals(vSwitchName)) {
                return vSwitch.getVSwitchId();
            }
        }
        return null;
    }

    @Override
    public void drop() {
        //nothing todo 不收费 无需释放
    }

    @Override
    public void create() throws AliyunPartsException {
        try {
            CreateVSwitchRequest createVSwitchRequest = new CreateVSwitchRequest();
            createVSwitchRequest.setZoneId("cn-hongkong-c");
            createVSwitchRequest.setVSwitchName(vSwitchName);
            createVSwitchRequest.setDescription("程序创建， 代理调换件， 请勿占用");
            createVSwitchRequest.setCidrBlock("172.16.0.0/24");
            createVSwitchRequest.setVpcId(configure.getVpcId());
            CreateVSwitchResponse createVSwitchResponse = callOpenApi(createVSwitchRequest);
            configure.setVSwitchId(createVSwitchResponse.getVSwitchId());
        } catch (Exception e) {
            throw new AliyunPartsException("创建交换机失败, 请检查秘钥是否正确");
        }

    }

    @Override
    public void start() {
        //nothing todo
    }

    @Override
    public void configure() {
        configure.setVSwitchId(getId());
    }
}
